package com.shinektv.vod.ksc;

import android.Manifest;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.shinektv.lrclib.LrcControlManager;
import com.shinektv.vod.ksc.databinding.ActivityMainBinding;
import com.shinektv.vod.ksclib.DefaultReadTextFile;
import com.shinektv.vod.ksclib.KscFile;
import com.shinektv.vod.ksclib.KscLine;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private final String TAG = MainActivity.class.getSimpleName();
    ActivityMainBinding binding = null;
    private List<KscLine> kscLines;
    private LrcControlManager mLrcControlManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                try {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                            Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, 0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                requestPermission();
            }
        } else {
            requestPermission();
        }
        binding = ActivityMainBinding.inflate(LayoutInflater.from(this));
        setContentView(binding.getRoot());

        initView();
        initListener();
    }

    private void initView() {
        if (binding == null) {
            Log.e(TAG, "initView: binding null");
            return;
        }
        binding.lrcTextView2.alignWithParent();

        AssetManager manager = getAssets();
        try {
            String[] files = manager.list("fonts");
            for (String file : files) {
                TextView tv = new TextView(this);
                tv.setTextSize(25);
                tv.setText("Hello World 你好世界 123  ————  " + file);
                tv.setTypeface(Typeface.createFromAsset(manager, "fonts/" + file));
                binding.llparent.addView(tv);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        mLrcControlManager = new LrcControlManager(this);
    }

    private View.OnClickListener mBtnOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();

            if (id == binding.btTestKsc.getId()) {
                testKsc();
            }
        }
    };

    private void initListener() {
        if (binding == null) {
            Log.e(TAG, "initView: binding null");
            return;
        }

        binding.btTestKsc.setOnClickListener(mBtnOnClickListener);

        binding.btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countDownTimer.start();
            }
        });

        binding.btnPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                countDownTimer.cancel();
                time = curPosition;
            }
        });
    }

    static List<String> kscList = new ArrayList<>();

    static {
        kscList.add("/sdcard/989314.ksc");
    }

    int kscIndex = 0;

    private String getKscPath() {
        String path = kscList.get((kscIndex++) % kscList.size());
        return path;
    }

    KscFile kscFile;

    private void testKsc() {
        index = 0;
        kscFile = new KscFile();
        String kscPath = getKscPath();
        if (!kscFile.open(kscPath,new DefaultReadTextFile())) {
            Log.e(TAG, String.format("testKsc: %s open failed", kscPath));
            return;
        }
        Log.i(TAG, String.format("testKsc: %s open succeed", kscFile));
        kscLines = kscFile.getKscLines();
        kscFile.printString();
        mLrcControlManager.setKscLines(kscLines);

//        kscFile.setScheduleListener(new SongScheduleListener() {
//            @Override
//            public void onSchedule(String songSchedule) {
//                if (!TextUtils.isEmpty(songSchedule) && !asdf.equals(songSchedule)) {
//                    if (songSchedule.equals(KscFile.SCHEDULE_CHORUS_START)) {
//                        if (asdf.equals(KscFile.SCHEDULE_INTERLUDE_START)) {
//                            Log.i(TAG, "_____" + time + "___SCHEDULE_INTERLUDE_STOP");
//                        }
//                    }
//                    Log.i(TAG, "____" + time + "____" + songSchedule);
//                    asdf = songSchedule;
//                }
//            }
//        });

        countDownTimer.start();
    }

    String asdf = "";
    //模拟歌曲总时长
    long millisInFuture = 5 * 60 * 1000;
    //歌曲暂停时的进度
    long time;
    //歌曲当前进度
    long curPosition;
    //演唱到第几行歌词
    int index = 0;
    CountDownTimer countDownTimer = new CountDownTimer(millisInFuture, 20) {
        @Override
        public void onTick(long millisUntilFinished) {
            curPosition = millisInFuture - millisUntilFinished + time + 19000;

            mLrcControlManager.showWordsOfSong(curPosition);

//            Log.i("------->", ""+l+", total = "+millisInFuture+", millisUntilFinished = "+millisUntilFinished+", time = "+time);
//            time = millisInFuture - millisUntilFinished;
//            String songSchedule = kscFile.getSongSchedule(time);

//            if (!TextUtils.isEmpty(songSchedule) && !asdf.equals(songSchedule)) {
//                if (songSchedule.equals(KscFile.SCHEDULE_CHORUS_START)) {
//                    if (asdf.equals(KscFile.SCHEDULE_INTERLUDE_START)) {
//                        Log.i(TAG, "___" + (millisInFuture - millisUntilFinished) + "_____SCHEDULE_INTERLUDE_STOP");
//                    }
//                }
//                Log.i(TAG, "___" + (millisInFuture - millisUntilFinished) + "_____" + songSchedule);
//                asdf = songSchedule;
//            }
        }

        @Override
        public void onFinish() {
            Log.i(TAG, "___" + millisInFuture + "_____SCHEDULE_SONG_STOP");
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (Settings.canDrawOverlays(this)) {
                requestPermission();
            }
        }
    }

    private void requestPermission() {
        String Permissionslist[] = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.INTERNET,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.RECORD_AUDIO

        };
        ActivityCompat.requestPermissions(this, Permissionslist, 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        countDownTimer.cancel();
    }
}